var express = require('express');
var router = express.Router();
var md5 = require('md5');
var User = require('../models/user');

router.get('/', (req, res) => {
  res.render('user', {
    title: '用户详情页'
  })
});

// GET /sigin 登录
router.get('/signin', (req, res, next) => {
  res.render('signin', {
    title: "用户登录",
    layout: false
  });
});

// POST /signin 登录
router.post('/signin', (req, res, next) => {
  req.checkBody('username', '请填写用户名 ！').notEmpty();
  req.checkBody('password', '请填写密码 ！').notEmpty()

  let [name, pwd] = [req.body.username, md5(req.body.password)];
  let errors = req.validationErrors();
  if (errors) {
    res.render('signin', req.body);
  }

  User.getUser(name, function (err, user) {
    console.log(user);
    if (user == null) {
      req.flash('error', '用户不存在！');
      res.redirect('/user/signup');
    }
    if (user.password !== pwd) {
      req.flash('error', '密码错误！');
      res.redirect('/user/signup');
    }
    if (user.username == name && user.password == pwd) {
        // 保存用户信息至session
        req.session.user = user;
        // 写入 flash
        req.flash('success', '用户登录成功');
        // 跳转页面
        res.redirect('/');
    }
  });
});
router.get('/user', () =>)


// GET /logout 登出
router.get('/logout', (req, res, next) => {
  res.render('logout', {
    title: "用户登出",
    layout: false
  });
});


// GET /siginup 注册
router.get('/signup', (req, res, next) => {
  res.render('signup', {
    title: "用户注册",
    layout: false
  });
});


// POST /siginup 注册
router.post('/signup', (req, res, next) => {
  req.checkBody('username', '请填写用户名 ！').notEmpty();
  req.checkBody('email', '请填写邮箱 ！').notEmpty().isEmail();
  req.checkBody('password', '请填写密码 ！').notEmpty()
  req.checkBody('confirm_password', '两次密码不匹配 ！').notEmpty().equals(req.body.password);

  let [name, pwd, email] = [req.body.username, md5(req.body.password), req.body.email];
  let errors = req.validationErrors();
  if (errors) {
    res.render('signup', req.body);
  }

  User.getUser(name, function (err, user) {
    if (user == null) {
      let user  =  new User({
        "username": name,
        "password": pwd,
        "email": email,
        "headimgurl": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1949665872,720897131&fm=111&gp=0.jpg",
        "create_at": new Date()
      });

      // 保存用户
      let promise = user.save();
      promise.then(function (user) {
        // 保存用户信息至session
        req.session.user = user;
        // 写入 flash
        req.flash('success', '用户注册成功');
        // 跳转页面
        res.redirect('/user/signin');
      })
      .catch(function (err) {
        // 写入 flash
        req.flash('error', '用户注册失败');
        res.redirect('/user/signup');
      });      
    }
    if (user != null && user.username == name) {
      req.flash('error', '用户已存在！');
      res.redirect('/user/signup');
    } 
  });
});



// POST /user/signout 登出
router.post('/signout', (req, res, next) => {
  // 清空 session 中用户信息
  req.session.user = null;
  req.flash('success', '登出成功');
  // 登出成功后跳转到主页
  res.redirect('/');  // 清空 session 中用户信息
});


// POST /user/:id/edit 修改资料
// router.post('/:id/edit', (req, res, next) => {

//   req.checkBody('username', '请填写用户名 ！').notEmpty();
//   req.checkBody('email', '请填写邮箱 ！').notEmpty().isEmail();
//   req.checkBody('password', '请填写密码 ！').notEmpty()

//   let [name, pwd, email] = [req.body.username, md5(req.body.password), req.body.email];
//   let errors = req.validationErrors();
//   if (errors) {
//     res.render('/user', req.body);
//   }

//   User.getUser(name, function (err, user) {
//     if (user == null) {
//       let user  =  new User({
//         "username": name,
//         "password": pwd,
//         "email": email,
//         "headimgurl": "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1949665872,720897131&fm=111&gp=0.jpg",
//         "create_at": new Date()
//       });

//       // 保存用户
//       let promise = user.save();
//       promise.then(function (user) {
//         // 保存用户信息至session
//         req.session.user = user;
//         // 写入 flash
//         req.flash('success', '用户注册成功');
//         // 跳转页面
//         res.redirect('/user/signin');
//       })
//       .catch(function (err) {
//         // 写入 flash
//         req.flash('error', '用户注册失败');
//         res.redirect('/user/signup');
//       });      
//     }
//     if (user != null && user.username == name) {
//       req.flash('error', '用户已存在！');
//       res.redirect('/user/signup');
//     } 
//   });
// });


// var checkNotLogin = require('../middlewares/check').checkNotLogin;

// // GET /signin 登录页
// router.get('/', checkNotLogin, function(req, res, next) {
//   res.send(req.flash());
// });

// // POST /signin 用户登录
// router.post('/', checkNotLogin, function(req, res, next) {
//   res.send(req.flash());
// });

module.exports = router;